package cn.edu.scnu.semart.order.untils;
import org.springframework.stereotype.Component;

@Component
public class SnowFlake {
    private long datacenterId = 1L; // 数据中心ID
    private long machineId = 1L; // 机器ID

    //private final long datacenterId;
    //private final long machineId;
    private long sequence = 0L;      // 序列号
    private long lastTimestamp = -1L;// 上次时间戳

    public SnowFlake() {
    }

    public synchronized long nextId() {
        long timestamp = System.currentTimeMillis();
        if (timestamp < lastTimestamp) {
            throw new RuntimeException("时钟回拨，拒绝生成ID");
        }

        if (timestamp == lastTimestamp) {
            sequence = (sequence + 1) & 4095; // 12位序列号
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }

        lastTimestamp = timestamp;

        // 64位ID = 1位符号位 + 41位时间戳 + 5位数据中心ID + 5位机器ID + 12位序列号
        return ((timestamp - 1609459200000L) << 22) // 1609459200000L是2021-01-01 00:00:00
                | (datacenterId << 17)
                | (machineId << 12)
                | sequence;
    }

    private long tilNextMillis(long lastTimestamp) {
        long timestamp = System.currentTimeMillis();
        while (timestamp <= lastTimestamp) {
            timestamp = System.currentTimeMillis();
        }
        return timestamp;
    }
}